package com.run_java_test.test6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/jars")
public class JarController {
    private final DynamicJarLoader jarLoader = new DynamicJarLoader();
    private final DynamicBeanRegistrar beanRegistrar;

    public JarController(DynamicBeanRegistrar beanRegistrar) {
        this.beanRegistrar = beanRegistrar;
    }

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    private JarClassLoader jarClassLoader;

    @PostMapping("/upload")
    public String uploadJar(@RequestParam("file") MultipartFile file) throws Exception {
        File tempDir = Files.createTempDirectory("uploaded-jars").toFile();
        File jarFile = new File(tempDir, file.getOriginalFilename());
        file.transferTo(jarFile);

        jarClassLoader = new JarClassLoader(jarFile.toURI().toURL());
        List<Class<?>> classes = jarClassLoader.loadAllClasses("com.run_java_test");
        for (Class<?> clazz : classes) {
            // beanRegistrar.registerClass(clazz);
            beanRegistrar.registerController(clazz);
        }
        return "JAR uploaded and classes registered.";
    }

    @PostMapping("/unload")
    public String unloadJar(@RequestParam("file") MultipartFile file) throws Exception {
        File tempDir = Files.createTempDirectory("uploaded-jars").toFile();
        File jarFile = new File(tempDir, file.getOriginalFilename());
        file.transferTo(jarFile);

        jarClassLoader = new JarClassLoader(jarFile.toURI().toURL());
        List<Class<?>> classes = jarClassLoader.loadAllClasses("com.run_java_test");
        for (Class<?> clazz : classes) {
            // beanRegistrar.registerClass(clazz);
            beanRegistrar.registerController2(clazz);
        }
        return "123";
//        try {
//            beanRegistrar.unregisterController2(file);
//            if (jarClassLoader != null) {
//                jarClassLoader.close();
//                jarClassLoader = null;
//            }
//            System.out.println("Unloaded JAR and removed all routes.");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "Failed to unload JAR.";
//        }
//        return "JAR unloaded successfully.";
    }

}
